package com.hangyutech.strelitzia.page;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

/**
 * Created by Andy on 2019/5/21.
 */


@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class OraclePagingInterceptor extends AbstractPagingInterceptor {

    @Override
    protected String getSelectTotalSql(String targetSql) {
        String sql = targetSql.toLowerCase();
        StringBuilder sqlBuilder = new StringBuilder(sql);

        int orderByPos;
        if ((orderByPos = sqlBuilder.lastIndexOf(ORDER_BY)) != -1) {
            sqlBuilder.delete(orderByPos, sqlBuilder.length());
        }
        sqlBuilder.insert(0, "select count(*) as _count from ( ").append(" )");

        return sqlBuilder.toString();
    }

    @Override
    protected String getSelectPagingSql(String targetSql, PagingBounds bounds) {
        String sql = targetSql.toLowerCase();
        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append("select * from ( select table_alias.*, rownum mybatis_rowno from ( ");
        sqlBuilder.append(sql);
        sqlBuilder.append(" ) table_alias where rownum <= ");
        sqlBuilder.append(bounds.getSelectCount());
        sqlBuilder.append(" ) where mybatis_rowno >= ");
        sqlBuilder.append(bounds.getOffset() + 1);

        return sqlBuilder.toString();
    }

}